<template>
	<view class="store-page">
		<scroll-view scroll-y="true" class="content-box">

			<uni-forms :rules="rules" :value="form" ref="form" validate-trigger="bind" err-show-type="undertext"
				label-width="400rpx">

				<view class="basic-information">
					<uni-forms-item label="品牌" label-width="200rpx" name="brand">
						<input type="text" v-model="form.brand" placeholder="请填写" />
					</uni-forms-item>

					<uni-forms-item label="手机号" label-width="200rpx" name="phone">
						<input type="text" v-model="form.phone" placeholder="请填写" />
					</uni-forms-item>
					<uni-forms-item label="车辆类型" label-width="400rpx">
						<view class="flex-reverse" @click="selectEntry(1)">
							<view class="selct-placeholder" v-if="form.vehicleType == ''">请选择</view>
							<view v-else>
								{{ form.vehicleName }}
							</view>
							<u-icon name="arrow-right"></u-icon>
						</view>

					</uni-forms-item>
					<uni-forms-item label="颜色" label-width="200rpx" name="colour">
						<input type="text" v-model="form.colour" placeholder="请填写" />
					</uni-forms-item>

					<uni-forms-item label="指导价" label-width="200rpx" name="guidePrice">
						<view class="input-flex">
							<input type="text" v-model="form.guidePrice" placeholder="请填写" />
							<text class="input-text">万元</text>
						</view>
				
					</uni-forms-item>


					<uni-forms-item label="车源所在地" label-width="200rpx" name="legalPersonName">
						<view class="flex-reverse" @click="changeRegionString">
							<view class="selct-placeholder" v-if="form.vehicleLocation == ''">请选择</view>
							<view v-else>
								{{ form.vehicleLocation }}
							</view>
							<u-icon name="arrow-right"></u-icon>
						</view>
					</uni-forms-item>

					<uni-forms-item label="寻车有效期" label-width="200rpx" name="legalPersonPhone">
						<view class="flex-reverse" @click="selectTime">
							<view class="selct-placeholder" v-if="form.lockForTime == ''">请选择</view>
							<view v-else>
								{{ form.lockForTime }}
							</view>
							<u-icon name="arrow-right"></u-icon>
						</view>
					</uni-forms-item>
					<uni-forms-item label="备注" label-width="200rpx" name="guidePrice">
						<input type="text" v-model="form.remark" placeholder="请填写" />
					</uni-forms-item>
					<view class="information-upload">
					<uni-forms-item>
						<template slot="label">
							<view class="formTitle-item">车辆照片</view>
						</template>
						<view class="imgs imgs-more">
							<u-upload :fileList="fileImage.operationSitePhotos" @afterRead="afterRead"
								@delete="deletePic" name="operationSitePhotos" multiple :maxCount="sitePhotosMaxCount"
								:previewFullImage="false" width="200rpx" height="200rpx" ></u-upload>
						</view>
					</uni-forms-item>
					
					</view>
				</view>


			</uni-forms>
		</scroll-view>
		<you-bottom-btn :btnConfig="bottomBtnConfig" v-if="isApproved != 2" @clickSubmit="clickSubmit"></you-bottom-btn>
		<u-datetime-picker :show="isShowTime" mode="date" ref="datetimePicker" :minDate="Number(new Date())"
			v-model="timeValue" @cancel="isShowTime = false" @confirm="selectTimeConfirm"></u-datetime-picker>
		<u-popup :show="isSelectShow" :round="12" mode="bottom" @close="isSelectShow = false">
			<view class="select-cotent">
				<view class="select-list">
					<view class="select-item" v-for="(item, index) in options" @click="selectItem(item)">
						{{ item.name }}
					</view>
				</view>
				<view class="select-item" @click="isSelectShow = false">
					取消
				</view>
			</view>
		</u-popup>

		<liu-choose-address ref="scroll" @change='chooseSuccess' :key="isAddress"></liu-choose-address>

	</view>
</template>

<script>
import zlxlsUploadImg from "@/components/zlxls-upload-img/zlxls-upload-img.vue"
import {
	baseUrl,
	baseImgUrl
} from '@/config'
import pageConfig from '@/config'
import { timestampToDate, forrmatterEnmu } from '@/utils/index.js'

import settleIn from '@/api/settleIn.js'
import { getToken, removeToken } from '@/utils/auth'
import { toast, showConfirm, tansParams } from '@/utils/common'
import Common from '@/api/common.js'
import login from "../../api/login"
export default {
	name: 'Store',
	components: { zlxlsUploadImg },
	data() {
		return {
			isShowTime: '',
			titleEntrn: "买车",
			uploadUrl: baseUrl + "/common/upload",
			sexs: [{
				text: '上架',
				value: 1
			}, {
				text: '下架',
				value: 2
			}],
			form: {
				id: '',  //id
				userId: '',  //用户id
				brand: '',  //品牌
				vehicleType: '', // 车辆类型 1新车 2二手车 3新能源
				vehicleName: '',
				status: '',  //1上架 2下架
				phone: '',  //手机号
				colour: '',//颜色
				vehicleModel: '', //车型
				guidePrice: '', //指导价
				province: '', //上牌地址 省code
				city: '', //上牌地址 市code
				vehicleLocation: '', //车源所在地
				lockForTime: '', //寻车有效期
				issueAddress: '', //1后台发布卖车 2小程序用户发布买车
				remark: '', //备注
				images:'',
				createTime: '', //创建时间
				updateTime: '', //修改时间
			},
			fileImage: {
				businessLicense: [],
				roadTransportPermit: [],
				legalPersonIdCardFront: [],
				legalPersonIdCardBack: [],
				businessLeaderIdCardFront: [],
				businessLeaderIdCardBack: [],
				operationSitePhotos: [],
			},
			header: {
				'Authorization': 'Bearer ' + getToken()
			},
			params: {
				cover: '',
				slider: '',
			},
			entryType: 1,
			imageValue: '',
			rules: {
				phone: {
					rules: [{
						required: true,
						errorMessage: '请填写电话',
					},
					{
						minLength: 11,
						maxLength: 11,
						errorMessage: '请填写正确电话长度',
					}
					],
				},
			},
			bottomBtnConfig: [{
				text: '上传买车信息',
				class: 'confirm',
				funcName: 'clickSubmit'
			}],
			isSelectShow: false,
			options: [],
			cityObject: {
				province: '',
				provinceString: '',
				city: '',
				cityString: '',
				region: '',
				regionString: '',
				aimProvince: '',
				aimProvinceString: '',
				aimCity: '',
				aimCityString: '',
				aimRegion: '',
				aimRegionString: ''
			},
			isApproved: 0,
			isAddress: true,
			sitePhotosMaxCount: 1,
			sale:'',
		}
	},

	async onLoad(e) {
		console.log(e.type,'eee')
		if (e.type == 'true') {
			this.titleEntrn = '新增'
			this.sale = e.type
				this.bottomBtnConfig[0].text = '提交'
		}else{
			this.titleEntrn = '新增'
			this.sale = e.type
			this.bottomBtnConfig[0].text = '提交'
		}
		uni.setNavigationBarTitle({
			title: this.titleEntrn
		});
		

	},
	async onShow() {

	},
	mounted() {
		const systemInfo = uni.getSystemInfoSync();
	},
	methods: {

		changeRegionString() {
			this.isAddress = !this.isAddress
			console.log('改变起始地')
			this.type = 1
			this.$refs.scroll.open()
		},

		//地址选择成功
		chooseSuccess(e) {
			console.log('省市区选择', e)
			if (this.type == 1) {
				this.form.province = e.value[0].value,
					this.form.city = e.value[1].value,
					this.form.vehicleLocation = e.value[0].label + e.value[1].label

				console.log('始发地', this.form.vehicleLocation)
			}
		},

		selectTime(flag) {
			// 1、托运时间 2、截止时间
			this.isShowTime = true;
			console.log(flag, 'flag')
			this.selectTimeFlag = flag;

			this.timeValue = Number(new Date())
			if (this.form.lockForTime && this.form.lockForTime != '') {
				this.timeValue = Number(new Date(this.form.lockForTime.replace(/-/g, '/')));
			}



		},
		selectTimeConfirm(e) {
			console.log(this.timeValue)
			let time = timestampToDate(e.value, 'ymd');
			this.form.lockForTime = time;
			this.isShowTime = false;
		},



		selectEntry(e) {
			if (e == 1) {
				this.options = [
					{
						name: '新车',
						value: '1',
					},
					{
						name: '二手车',
						value: '2',
					},
					{
						name: '新能源',
						value: '3',
					},
				]
			}
			this.isSelectShow = true;
		},
		selectItem(item) {
			this.form.vehicleType = item.value
			this.form.vehicleName = item.name
			this.isSelectShow = false;
		},
		select(e) {
		},
		async clickSubmit() {

			this.form.userId = uni.getStorageSync('userId')
			if (this.form.brand == '') {
				uni.showToast({
					title: "请填写品牌",
					icon: "none"
				})
				return;
			}

			if (this.form.phone == '') {
				uni.showToast({
					title: "请填写手机号",
					icon: "none"
				})
				return;
			}

			if (this.form.vehicleType == '') {
				uni.showToast({
					title: "请选择车辆类型",
					icon: "none"
				})
				return;
			}

			if (this.form.colour == '') {
				uni.showToast({
					title: "请填写颜色",
					icon: "none"
				})
				return;
			}

			if (this.form.vehicleLocation == '') {
				uni.showToast({
					title: "请选择车源所在地",
					icon: "none"
				})
				return;
			}

			if (this.form.lockForTime == '') {
				uni.showToast({
					title: "请选择寻车有效期",
					icon: "none"
				})
				return;
			}
			
			if (this.form.images  == '') {
				uni.showToast({
					title: "请上传车辆照片",
					icon: "none"
				})
				return;
			}
			
			let res= null
			if (this.sale == 'true') {
				res = await settleIn.saveAdminIssue({ ...this.form });
			}else{
				res = await settleIn.saveUserIssue({ ...this.form });
			}
			
		
			if (res.code == 200) {
				uni.showToast({
					title: "操作成功",
					icon: 'none'
				});
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/models'
					})
				}, 1000)
			}
		},
		deletePic(event) {
			this.fileImage[`${event.name}`].splice(event.index, 1);
			console.log(this.fileImage[`${event.name}`])
		},

			// 新增图片
			async afterRead(event) {
				console.log(event)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file);
				let fileListLen = this.fileImage[`${event.name}`].length;
				lists.map((item) => {
					this.fileImage[`${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					try{
						const result = await this.uploadFilePromise(lists[i].url)
						// 返回给后端服务器的 结果需要赋值给 this.infoForm.image = result
						console.log(result, '上传图像result');
						this.form.images = result.url
						let item = this.fileImage[`${event.name}`][fileListLen];
						this.fileImage[`${event.name}`].splice(fileListLen, 1, Object.assign(item, {
							status: result.code,
							message: result.code != '200' ? '上传失败' : '上传成功',
							url: result.fileName
						}))
						fileListLen++
					}catch(e){
						//TODO handle the exception
						this.fileImage[`${event.name}`].splice(fileListLen, 1)
					}
					
				}
			},
			uploadFilePromise(url, index) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseUrl + '/common/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: {
							'Authorization': 'Bearer ' + getToken()
						},
						formData: {},
						success: (respose) => {
							let res = respose.data && JSON.parse(respose.data);
							console.log(res, "resresresres")
							if(res.code == 401) {
								showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?').then(reslv => {
								  if (reslv.confirm) {
								    removeToken()
								    uni.reLaunch({ url: '/subPages/login/index' })
								  }
								})
							} else if(res.code == 200) {
								setTimeout(() => {
									resolve(res)
								}, 1000)
							} else {
								uni.showToast({
									icon: 'none',
									title: '上传失败，请稍后再试'
								})
								reject("err")
							}
							
						},
						fail: (err) => {
							console.log(err,"err");
							
						}
					});
				})
			},
			


		forrmatterCompany(id) {
			// let index = this.operatingCompany.findIndex(ele => ele.id == id);
			// return index > -1 ? this.operatingCompany[index].companyName : id;
		}
	}
}
</script>
<style lang="scss" scoped>
/deep/.u-upload__wrap__preview {
	margin: 0;
}

.imgs-more {
	/deep/.u-upload__wrap__preview {
		margin-right: 10rpx;
		margin-bottom: 10rpx;
	}
}

.select-cotent {
	font-size: 34rpx;
	color: #161823;
	background: #f3f3f3;
	overflow: hidden;
	border-radius: 12rpx 12rpx 0 0;

	.select-list {
		margin-bottom: 16rpx;
		background: #fff;
		max-height: 40vh;
		overflow-y: auto;
	}

	.select-item {
		padding: 32rpx;
		text-align: center;
		background: #fff;
	}
}

.store-page {
	background: #f6f6f6;

	.content-box {
		padding: 0 28rpx;
		padding-bottom: 220rpx;
		height: 100vh;
		margin-top: 20rpx;

		.formTitle {
			font-weight: 500;
			color: #1a1a1a;
			margin: 20rpx 0;
			font-size: 28rpx;

			text {
				color: red;
			}
		}

		.formTitle-item {
			font-weight: 500;
			color: #666;
			font-size: 28rpx;
			margin-bottom: 10rpx;
			margin-top: 30rpx;
		}

		.basic-information,
		.information-upload {
			background: #fff;
			padding: 10rpx 24rpx;
			border-radius: 10rpx;
		}
			
		.information-upload{
			padding: 0rpx;
		}

		.basic-information {
			input {
				height: 100rpx;
				font-size: 28rpx;
				text-align: right;
			}
			.flex-reverse{
				height: 100rpx;
				font-size: 28rpx;
				text-align: right;
				display: flex;
				align-items: center;
			}
		}
	}
}

.selct-placeholder {
	color: #999;
	font-size: 28rpx;
	text-align: right;
}

.flex-reverse {
	height: 100%;
	display: flex;
	justify-content: flex-end;
	align-items: center;
	line-height: 1;
}
</style>
<style lang="scss">
.basic-information {

	.uni-group__content,
	.information-upload {
		border-radius: 20rpx !important;

	}

	.uni-forms-item__label {
		width: 250rpx !important;
	}

	.uni-forms-item {
		align-items: center;
		margin: 0;
		border-bottom: 1px solid #e9e9e9;

		&:last-child {
			border: 0;
		}
	}
}

.information-upload {
	.uni-forms-item {
		display: block;

	}
}

.imgs {
	display: flex;
	justify-content: space-between;

	.imgs-item {
		width: 312rpx;
		background: #F6F6F6;
		padding: 30rpx 20rpx;
		padding-bottom: 16rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		border-radius: 8rpx;
		flex: 1;

		&:nth-child(2n + 1) {
			margin-right: 20rpx;
		}

		>text {
			color: #222;
			font-size: 24rpx;
			line-height: 1;
			padding-top: 16rpx;
		}

		image {
			width: 240rpx;
			height: 170rpx;
		}
	}
}

.msg--active {
	opacity: 1;
	transform: translateY(-100%);
}

.checkbox {
	margin-left: 170rpx;

	.uni-data-checklist .checklist-group .checklist-box {
		margin-right: 0rpx;
		margin-left: 12rpx;
	}
}

.input-flex{
	display: flex;
	align-items: center;
	margin-left: 40rpx;
}
	
.input-text{
	font-size: 28rpx;
	color: #666;
	margin-left: 10rpx;
}
</style>